package org.feng.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.feng.api.sys.logs.LogVO;
import org.feng.bo.AddOperateLogRequest;
import org.feng.entity.OperateLog;
import org.feng.mapper.OperateLogMapper;
import org.feng.service.IOperateLogService;
import org.feng.util.TimeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 操作日志服务实现
 *
 * @author feng
 */
@Slf4j
@Service
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements IOperateLogService {
    @Override
    public void addLog(AddOperateLogRequest request) {
        // todo 待完善
    }

    @Override
    public List<LogVO> queryByQueryId(String queryId) {
        if (StringUtils.isBlank(queryId)){
            return Collections.emptyList();
        }
        LambdaQueryWrapper<OperateLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OperateLog::getQueryId,queryId);
        queryWrapper.orderByDesc(OperateLog::getCreateTime);
        List<OperateLog> operateLogs = this.getBaseMapper().selectList(queryWrapper);
        if (CollectionUtils.isEmpty(operateLogs)){
            return new ArrayList<>();
        }

        return operateLogs.stream().map(this::buildVo).collect(Collectors.toList());
    }

    private LogVO buildVo(OperateLog operateLog) {
        LogVO logVO = new LogVO();
        JSONObject ext = operateLog.getExt();
        BeanUtils.copyProperties(operateLog, logVO, "ext", "createTime");
        LocalDateTime createTime = operateLog.getCreateTime();
        if (createTime != null) {
            logVO.setCreateTime(TimeUtil.parse(createTime));
        }
        logVO.setExt(ext);
        return logVO;
    }
}
